package com.hliushi.netty.server.handler;

import com.hliushi.netty.server.session.Session;
import com.hliushi.netty.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author llhuang10
 * @date 2021/10/22 12:27
 */
@Slf4j
@ChannelHandler.Sharable
public class QuitHandler extends ChannelInboundHandlerAdapter {


    /**
     * 当连接断开时触发 inactive 事件
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Session session = SessionFactory.getSession();
        String username = session.getUsername(ctx.channel());
        session.unbind(ctx.channel());
        log.debug("{} 已经断开", username);
    }


    /**
     * 当出现异常时, 触发事件
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Session session = SessionFactory.getSession();
        String username = session.getUsername(ctx.channel());
        session.unbind(ctx.channel());
        log.debug("{} 已经异常断开 异常: {}", username, cause.getMessage());
    }
}
